﻿/**********************************************************************************
 * Project Name :   
 * Remarks      :  
 * Class Name   :  UserService 
 * Version      :  v1.0.0.0 
 * Author       :  Joey Liang 
 * Description  :  
 * Created Time :  2013/10/31 22:44:22
 * Update Man   :  Joey Liang
 * Update Time  :  2013/10/31 22:44:22
************************************************************************/

using IdleTest.EFAndMVCDemo.IRepositories;
using IdleTest.EFAndMVCDemo.IServices;
using IdleTest.EFAndMVCDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IdleTest.EFAndMVCDemo.Services
{
    public class UserService : IUserService
    {
        private IUserRepository userRepository;

        public UserService(IUserRepository userRepository)
        {
            // TODO: Complete member initialization
            this.userRepository = userRepository;
        }

        #region IUserService成员
        public bool Login(UserModel model)
        {
            if (!IsValidModel(model))
            {
                return false;
            }

            IList<UserModel> list = 
                userRepository.Get(p => p.LoginName == model.LoginName && p.Password == model.Password).ToList();

            return list != null && list.Count > 0;
        }

        public bool Register(UserModel model)
        {
            if (!IsValidModel(model))
            {
                return false;
            }

            if (GetModel(model.LoginName) != null)
            {
                return false;
            }

            userRepository.Insert(model);
            return true;
        }

        public UserModel GetModel(string loginName)
        {
            if (!string.IsNullOrEmpty(loginName))
                return userRepository.GetSingle(loginName);

            return null;
        }
        #endregion

        private bool IsValidModel(UserModel model)
        {
            return model != null && !string.IsNullOrEmpty(model.LoginName) && !string.IsNullOrEmpty(model.Password);
        }
    }
}
